<?php

namespace App\Http\Controllers\Admin\Flying;

use Carbon\Carbon;
use App\Enums\FlyingEnum;
use App\Response\Response;
use App\Enums\RedisKeyEnum;
use App\Jobs\QiPao\ExcelJob;
use App\Services\Tools\DateTime;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\HelperService;
use \App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class FlyingController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->is_next = $request->input('is_next', 0);
        if (!in_array($this->is_next, [0, 1])) {
            throw new BasicException(0, '参数有误');
        }
        $this->pot_name = '';
        if ($this->is_next) {
            $this->type = $request->input('type', FlyingEnum::POOL_TYPE_HUNDRED_NEXT);
            if (isset(FlyingEnum::POOL_TYPE_CONFIG_NEXT[$this->type])) {
                $this->pot_name = FlyingEnum::POOL_TYPE_CONFIG_NEXT[$this->type];
            }
        } else {
            $this->type = $request->input('type', FlyingEnum::POOL_TYPE_HUNDRED);
            if (isset(FlyingEnum::POOL_TYPE_CONFIG[$this->type])) {
                $this->pot_name = FlyingEnum::POOL_TYPE_CONFIG[$this->type];
            }
        }
    }

    /**
     * @apiDescription type:1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiVersion 0.1.0
     * @apiName 本期奖池
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiSuccessExample 成功响应
     */
    public function index(Request $request)
    {
        $list = app('repo_flying')->getJackpotList($this->type, $this->is_next);
        return Response::sendData([
            'left'  => app('repo_flying')->getJackpotCount($this->type, $this->is_next),        //获取剩余次数
            'total' => app('repo_flying')->getJackpotTotal($this->type, $this->is_next),        //获取剩余总金额
            'type'  => $this->type,
            'name'  => $this->pot_name,
            'list'  => $list,
        ]);
    }

    /**
     * @Desc:下期奖池列表
     * @param  Request  $request
     * @return string
     * @author: shiquan
     * @Time: 2023/3/7 15:43
     */
    public function next(Request $request)
    {
        $id = $request->input('id',0);
        if ($id <= 0){
            throw new BasicException(0, '请选择奖池配置id');
        }
        $list = app('repo_flying')->getJackpotNextList($id,1);
        $config = app('model_flying_next_config')->where('id', $id)->first();
        if (empty($config)){
            throw new BasicException(0, '请先配置奖池');
        }
        return Response::sendData([
            'left'  => app('repo_flying')->getJackpotCount($config['type'], 1, $id),        //获取剩余次数
            'total' => app('repo_flying')->getJackpotTotal($config['type'], 1, $id),        //获取剩余总金额
            'type'  => $config['type'],
            'name'  => $config['name'],
            'list'  => $list,
            'is_open' => $config['is_open']
        ]);
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 添加修改本期奖池礼物
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} id   如果传了id则为更新,否则添加,非必传
     * @apiParam {numeric} number   库存,必传
     * @apiParam {numeric} gift_id   礼物id,必传
     * @apiSuccessExample 成功响应
     */
    public function update(Request $request)
    {
        $data = $request->only(['gift_id', 'number']);
        $id = intval($request->input('id', 0));
        if (!isset($data['gift_id']) || $data['gift_id'] <= 0) {
            throw new BasicException(0, '请选择礼物');
        }
        if (!isset($data['number']) || $data['number'] < 0) {
            throw new BasicException(0, '数量不能小于0');
        }
        $model = $this->is_next ? 'model_flying_next' : 'model_flying_pool';
        if ($id > 0) {
            app($model)->where('id', $id)->update($data);
        } else {
            //礼物最多只能添加12个
            $count = app($model)->where('sold', 1)->where('type', $this->type)->count();
            if ($count >= 12){
                throw new BasicException(0, '礼物至多配置12个');
            }
            $info = app($model)->where('sold', 1)->where('type', $this->type)->where('gift_id', $data['gift_id'])->first();
            if ($info){
                throw new BasicException(0, '已存在该礼物,无法新增');
            }
            $data['type'] = $this->type;
            if (!$this->is_next) {
                $data['add_time'] = Carbon::now();
            }
            app($model)->insert($data);
        }

        return Response::sendData('success');
    }

    /**
     * @Desc:更新下一期奖池
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 15:45
     */
    public function updateNext(Request $request)
    {
        $data = $request->only(['gift_id', 'number', 'next_config_id']);
        $id = intval($request->input('id', 0));
        if (!isset($data['gift_id']) || $data['gift_id'] <= 0) {
            throw new BasicException(0, '请选择礼物');
        }
        if (!isset($data['number']) || $data['number'] < 0) {
            throw new BasicException(0, '数量不能小于0');
        }

        $model = 'model_flying_next';
        if ($id > 0) {
            if ($data['next_config_id']){
                unset($data['next_config_id']);
            }
            $info = app($model)->where('id', $id)->first();
            //如果是更新百连池,需要将补池礼物改为失效
            if ($info['type'] == FlyingEnum::POOL_TYPE_HUNDRED_NEXT && $info['gift_id'] != $data['gift_id']){
                app('model_flying_supplement_gift')->where('gift_id', $info['gift_id'])->update([
                    'is_delete' => 1
                ]);
            }
            app($model)->where('id', $id)->update($data);
        } else {
            if (empty($data['next_config_id'])){
                throw new BasicException(0, '请输入配置id');
            }
            $type = app('model_flying_next_config')->where('id', $data['next_config_id'])->value('type');
            //礼物最多只能添加12个
            $count = app($model)->where('sold', 1)->where('next_config_id', $data['next_config_id'])->count();
            if ($count >= 12){
                throw new BasicException(0, '礼物至多配置12个');
            }
            $info = app($model)->where('sold', 1)->where('next_config_id', $data['next_config_id'])->where('gift_id', $data['gift_id'])->first();
            if ($info){
                throw new BasicException(0, '已存在该礼物,无法新增');
            }
            $data['type'] = $type;
            app($model)->insert($data);
        }

        return Response::sendData('success');
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 一键修改本期奖池礼物
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} type   奖池类型,非必传 1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} gift_detail   礼物数据json  [{"gift_id":377,"gift_name":"拐杖糖","number":2301,"ratio":0}]
     * @apiSuccessExample 成功响应
     */
    public function editAll(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'gift_detail' => 'required|string',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data = $request->only(['gift_detail', 'next_config_id']);
        $giftDetailStr = $data['gift_detail'];
        $giftDetailList = json_decode($giftDetailStr, true);
        $model = $this->is_next ? 'model_flying_next' : 'model_flying_pool';
        if ($this->is_next && empty($data['next_config_id'])){
            throw new BasicException(10001, '奖池类型参数错误!');
        }
        foreach ($giftDetailList as $key => $value) {
            if (!isset($value['gift_id']) || $value['gift_id'] <= 0) {
                throw new BasicException(0, '请选择礼物');
            }
            if ($value['number'] < 0) {
                throw new BasicException(0, '数量不能小于0');
            }
            if ($value['ratio'] < 0) {
                throw new BasicException(0, '爆率不能小于0');
            }
            $whereArr = [];
            $whereArr[] = ["gift_id", "=", $value['gift_id']];
            $whereArr[] = ["type", "=", $this->type];
            if (!empty($data['next_config_id'])){
                $whereArr[] = ["next_config_id", "=", $data['next_config_id']];
            }
            app($model)->where($whereArr)->update(['number' => $value['number'], 'ratio' => $value['ratio']]);
        }

        return Response::sendData('success');
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 删除本期奖池礼物
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} id   主键id,必传
     * @apiSuccessExample 成功响应
     */
    public function delete(Request $request)
    {
        $id = $request->input('id', 0);
        $model = $this->is_next ? 'model_flying_next' : 'model_flying_pool';
        $detail = app($model)->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '数据有误');
        }
        app($model)->where('id', $id)->delete();

        return Response::sendData('success');
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 替换奖池
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} type   奖池类型,必传
     * @apiSuccessExample 成功响应
     */
    public function replace()
    {
        app('repo_flying')->replaceJackpot($this->type);

        return Response::sendData(1);
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 中奖纪录
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} page   page,非必传
     * @apiParam {numeric} perPage   perPage,非必传
     * @apiParam {string} datemin   开始时间如2021-03-11,非必传
     * @apiParam {string} datemax   结束时间如2021-03-12,非必传
     * @apiParam {number} gift_id   礼物id,非必传
     * @apiParam {string} keyword   用户编号或昵称,非必传
     * @apiParam {int} is_flutter 是否飘屏记录，1：是，0：否，-1（默认）：全部
     * @apiSuccessExample 成功响应
     */
    public function record(Request $request)
    {
        $list = app('repo_flying')->getRecord($request);

        return Response::sendData($list);
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 更新产出比
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} min_ratio   库存产出投入比最低下限,必传
     * @apiParam {numeric} max_ratio   库存产出投入比最大上限,必传
     * @apiParam {numeric} min_self_ratio   个人产出投入比最低下限,必传
     * @apiParam {numeric} max_self_ratio   个人产出投入比最大上限,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateRatio(Request $request)
    {
        $key = RedisKeyEnum::FLYING_FISH_RATIO_CONFIG;
        $minRatio = $request->input('min_ratio');
        $maxRatio = $request->input('max_ratio');
        $minSelfRatio = $request->input('min_self_ratio');
        $maxSelfRatio = $request->input('max_self_ratio');
        if ($minRatio <= 0 || $maxRatio <= 0 || $minSelfRatio <= 0 || $maxSelfRatio <= 0) {
            throw new BasicException(0, '概率配置不能小于等于0');
        }
        $redis = app('redis');
        $ratioConfig = [
            'min_ratio'      => $minRatio,
            'max_ratio'      => $maxRatio,
            'min_self_ratio' => $minSelfRatio,
            'max_self_ratio' => $maxSelfRatio,
        ];
        $redis->set($key, json_encode($ratioConfig));

        return Response::sendData(1);
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 用户产出比列表
     * @apiGroup 飞屋环球记
     * @apiParam {number} user_code 用户编号,非必传
     * @apiParam {number} nickname 用户昵称
     * @apiParam {number} mobile 用户编号,非必传
     * @apiParam {number} type 用户编号,非必传 与output配合使用 实际产出比 筛选 1:>output  2:<output 3：=output
     * @apiParam {number} output 用户编号,非必传
     * @apiParam {number} output_order 1根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
     * @apiParam {string} last_lottery_time_start 最后抽奖时间开始
     * @apiParam {string} last_lottery_time_end 最后抽奖时间结束
     * @apiParam {number} perPage 页码 ，非必传 默认20
     * @apiParam {number} page 用户编号,非必传
     * @apiSuccessExample 成功响应
     */
    public function userRatio(Request $request)
    {
        $keyword = $request->input('user_code');
        $nickname = $request->input('nickname', null);
        $mobile = $request->input('mobile', null);
        $output = $request->input('output', null);
        $type = $request->input('type', null);             //>= or <=
        $ordertype = $request->input('output_order', 1);   //>= or <=
        $lastLotteryTimeStart = $request->input('last_lottery_time_start', '');
        $lastLotteryTimeEnd = $request->input('last_lottery_time_end', '');
        $page = $request->input('page', 20);               //>= or <=
        $perPage = $request->input('perPage', 20);
        $data = $request->only(['user_code', 'nickname', 'mobile', 'output', 'type', 'output_order', 'perPage']);
        $va = app('validator')->make($data, [
            'perPage'      => 'integer|min:1',
            'page'         => 'integer|min:1',
            'user_code'    => 'integer|min:1',
            'mobile'       => 'string|max:11',
            'output_order' => 'in:1,2,3',//根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
            'output'       => 'numeric|min:0',
            'type'         => 'integer|in:1,2,3',//1:> 2:< 3:=

        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $where = [
            ['base.id', '>', 0],
        ];
        if ($keyword) {
            $where[] = ['ud.user_code', '=', $keyword];
        }
        if ($nickname) {
            $where[] = ['ud.nickname', 'like', '%' . $nickname . "%"];
        }
        if ($mobile) {
            $where[] = ['u.mobile', '=', $mobile];
        }


        if ($type && $type == 1 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '>', intval($output)];
        }
        if ($type && $type == 2 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '<', $output];
        }
        if ($type && $type == 3 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '=', $output];
        }
        if ($lastLotteryTimeStart) {
            $where[] = ['base.update_time', '>=', $lastLotteryTimeStart];
        }
        if ($lastLotteryTimeEnd) {
            $where[] = ['base.update_time', '<=', $lastLotteryTimeEnd];
        }

        $order = [];
        if ($ordertype == 1) {
            $order['field'] = 'base.id';
            $order['way'] = 'desc';
        } elseif ($ordertype == 2) {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'asc';
        } else {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'desc';
        }

        $field = [
            DB::raw('ROUND(base.outcoin_total/base.incoin_total,2) as current_ratio_real'),
            'base.id',
            'u.mobile',
            'base.incoin_total',
            'base.outcoin_total',
            'ud.nickname',
            'ud.head_picture',
            'ud.user_code',
        ];

        $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.'flying_user_record as base')
            ->leftJoin('ln_user_data as ud', 'base.user_id', '=', 'ud.user_id')
            ->leftJoin('ln_user as u', 'base.user_id', '=', 'u.user_id')
            ->select($field)
            ->where($where)
            ->orderBy($order['field'], $order['way'])
            ->paginate($perPage);

        $userRatioConfigKey = RedisKeyEnum::FLYING_FISH_USER_RATIO_CONFIG;
        $redis = app('redis');
        $userRatioConfig = $redis->get($userRatioConfigKey);

        if (empty($userRatioConfig)) {
            $userRatioConfig = [
                'user_incoin'  => 20000,
                'user_outcoin' => 20000,
            ];
            $redis->set($userRatioConfigKey, json_encode($userRatioConfig));
        } else {
            $userRatioConfig = json_decode($userRatioConfig, true);
        }

        $list->getCollection()->transform(function ($value) use ($userRatioConfig) {
            if ($value->incoin_total > 2 * $userRatioConfig['user_incoin'] && $value->outcoin_total > 2 * $userRatioConfig['user_outcoin']) {//用户投入产出都在计划的两倍以上
                $timesIncoin = ceil($value->incoin_total / $userRatioConfig['user_incoin']);                                                 //用户实际投入/计划投入 倍率
                $timesOutcoin = ceil($value->outcoin_total / $userRatioConfig['user_outcoin']);
                $times = min($timesIncoin, $timesOutcoin);
                $value->current_incoin_total = $value->incoin_total - ($times - 2) * $userRatioConfig['user_incoin'];
                $value->current_outcoin_total = $value->outcoin_total - ($times - 2) * $userRatioConfig['user_outcoin'];
                $value->current_ratio = round($value->current_outcoin_total / $value->current_incoin_total, 2);
//                $value->current_ratio_real = round($value->current_ratio_real , 2);
            } else {
                $value->current_incoin_total = $value->incoin_total;
                $value->current_outcoin_total = $value->outcoin_total;
                $value->current_ratio = $value->current_incoin_total == 0 ? 0 : round($value->current_outcoin_total / $value->current_incoin_total, 2);
//                $value->current_ratio_real = round($value->current_ratio_real , 2);
            }

            return $value;
        });

        return Response::sendList($list, [], $userRatioConfig);
    }

    /**
     * @apiVersion 0.1.0
     * @apiName 用户投入产出比配置修改
     * @apiGroup 飞屋环球记
     * @apiParam {numeric} user_incoin   用户理论投入,必传
     * @apiParam {numeric} user_outcoin   用户理论产出,必传
     * @apiSuccessExample 成功响应
     */
    public function updateUserRatio(Request $request)
    {
        $key = RedisKeyEnum::FLYING_FISH_USER_RATIO_CONFIG;
        $userIncoin = $request->input('user_incoin');
        $userOutcoin = $request->input('user_outcoin');
        if ($userIncoin <= 0 || $userOutcoin <= 0) {
            throw new BasicException(0, '投入及产出配置不能小于等于0');
        }
        $redis = app('redis');
        $userRatioConfig = [
            'user_incoin'  => $userIncoin,
            'user_outcoin' => $userOutcoin,
        ];
        $redis->set($key, json_encode($userRatioConfig));

        return Response::sendData(1);
    }

    /**
     * @Desc:统计数据-总数据
     * @return string
     * @author: shiquan
     * @Time: 2023/3/7 14:44
     */
    public function allData()
    {
        $data = app('repo_flying')->allData();

        return Response::sendData($data);
    }

    /**
     * @Desc:盈利/亏损用户列表
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 15:17
     */
    public function usersList(Request $request)
    {
        //数据过滤
        $v = app('validator')->make($request->all(), [
            'page_size' => 'filled|numeric',
            'page' => 'filled|numeric',
            'user_code' => 'filled|string',
            'type' => 'required|in:1,2'
        ]);

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        $params = $request->input();
        $params['user_code'] = $params['user_code'] ?? -1;
        $params['page'] = $params['page'] ?? 1;
        $params['page_size'] = $params['page_size'] ?? 10;
        $params['start_time'] = $params['start_time'] ?? '';
        $params['end_time'] = $params['end_time'] ?? '';
        $params['time_type'] = $params['time_type'] ?? 0;
        if ($params['time_type'] == 1){     //今日
            $dateRange = [date('Y-m-d'), date('Y-m-d')];
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 2){   //本周
            $dateRange = DateTime::getWeekDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 3){       //本月
            $dateRange = DateTime::getMonthDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        }
        if (strtotime($params['end_time']) - strtotime($params['start_time']) > 180 * 86400) {
            throw new BasicException(0, '日期范围不能超过180天');
        }
        if (!empty($params['start_time'])){
            $params['start_time'] = $params['start_time'].' 00:00:00';
        }

        if (!empty($params['end_time'])){
            $params['end_time'] = $params['end_time'].' 23:59:59';
        }

        $profitData = app('repo_flying')->userList($params);

        return Response::sendData($profitData);
    }

    /**
     * @Desc:列表导出
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 15:17
     */
    public function export(Request $request)
    {
        //数据过滤
        $v = app('validator')->make($request->all(), [
            'page_size' => 'nullable|numeric',
            'page' => 'nullable|numeric',
            'user_code' => 'nullable|string',
            'type' => 'required|in:1,2',
        ]);

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        $params = $request->all();
        $params['time_type'] = $params['time_type'] ?? 0;
        if ($params['time_type'] == 1){     //今日
            $dateRange = [date('Y-m-d'), date('Y-m-d')];
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 2){   //本周
            $dateRange = DateTime::getWeekDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 3){       //本月
            $dateRange = DateTime::getMonthDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        }
        if (strtotime($params['end_time']) - strtotime($params['start_time']) > 180 * 86400) {
            throw new BasicException(0, '日期范围不能超过180天');
        }
        if (!empty($params['start_time'])){
            $params['start_time'] = $params['start_time'].' 00:00:00';
        }

        if (!empty($params['end_time'])){
            $params['end_time'] = $params['end_time'].' 23:59:59';
        }
        $type = $params['type'];
        if ($type == 1){
            /*奖池数据统计-盈利用户列表*/
            $data = [
                'admin_id'     => $request->admin_id ?? '',
                'data_no'      => 36,//ExportEnum::NO
                'condition'    => json_encode($params) ?? '',
                'status'       => 0,//正在导出
                'title'        => '飞屋环球记奖池数据统计-盈利用户列表 异步导出',//正在导出
                'download_url' => '',
            ];
            $exportLogId = app('model_admin_export_log')->insertGetId($data);
            $excel = new ExcelJob($exportLogId, $request->admin_id, 36, $params);
            // 标记导出程序开始运行
            dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));                    //推送到指定队列
        } else {
            /*奖池数据统计-亏损用户列表*/
            $data = [
                'admin_id'     => $request->admin_id ?? '',
                'data_no'      => 37,//ExportEnum::NO
                'condition'    => json_encode($params) ?? '',
                'status'       => 0,//正在导出
                'title'        => '飞屋环球记奖池数据统计-亏损用户列表 异步导出',//正在导出
                'download_url' => '',
            ];
            $exportLogId = app('model_admin_export_log')->insertGetId($data);
            $excel = new ExcelJob($exportLogId, $request->admin_id, 37, $params);
            // 标记导出程序开始运行
            dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));                    //推送到指定队列
        }

        return Response::sendData(true);
    }

    /**
     * @Desc:下期奖池管理列表
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:00
     */
    public function nextConfig(Request $request)
    {
        $list = app('repo_flying')->getNextConfig();

        return Response::sendData($list);
    }

    /**
     * @Desc:下期奖池管理类型
     * @return string
     * @author: shiquan
     * @Time: 2023/3/13 18:11
     */
    public function nextConfigType()
    {
        $data = [
            [
                'type' => FlyingEnum::POOL_TYPE_ONE_NEXT,
                'value' => '1连奖池'
            ],[
                'type' => FlyingEnum::POOL_TYPE_TEN_NEXT,
                'value' => '10连奖池'
            ],[
                'type' => FlyingEnum::POOL_TYPE_HUNDRED_NEXT,
                'value' => '100连奖池'
            ],[
                'type' => FlyingEnum::POOL_TYPE_NEW_NEXT,
                'value' => '新手奖池'
            ]
        ];
        return Response::sendData($data);

    }

    /**
     * @Desc:新增下期管理奖池
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:00
     */
    public function nextConfigAdd(Request $request)
    {
        $param = $request->only('name', 'type');
        $v = app('validator')->make($param, [
            'name' => 'required|string',
            'type' => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        app('repo_flying')->nextConfigAdd($param);

        return Response::sendData(true);
    }

    /**
     * @Desc:编辑下期管理奖池
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:00
     */
    public function nextConfigEdit(Request $request)
    {
        $param = $request->only('id', 'name', 'type');
        $v = app('validator')->make($param, [
            'id'   => 'required|integer',
            'name' => 'required|string',
            'type' => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        app('repo_flying')->nextConfigEdit($param);

        return Response::sendData(true);
    }

    /**
     * @Desc:删除下期管理奖池
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:01
     */
    public function nextConfigDel(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id'   => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        app('repo_flying')->nextConfigDel($param);

        return Response::sendData(true);
    }

    /**
     * @Desc:下期奖池配置开关
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:11
     */
    public function nextConfigOpen(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id'   => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $isOpen = app('repo_flying')->nextConfigOpen($param);

        return Response::sendData(true, $isOpen === 0 ? '关闭成功' : '开启成功');
    }

    /**
     * @Desc:补池配置详情
     * @return string
     * @author: shiquan
     * @Time: 2023/3/8 11:23
     */
    public function supplementConfigInfo()
    {
        $result = app('repo_flying')->supplementConfigInfo();

        return Response::sendData($result);
    }

    /**
     * @Desc:更新补池配置
     * @return string
     * @author: shiquan
     * @Time: 2023/3/8 11:23
     */
    public function supplementConfigUpdate(Request $request)
    {
        $params = $request->only(['rate', 'min_num']);
        if (isset($params['rate']) && ($params['rate'] > 1 || $params['rate'] < 0)){
            throw new BasicException(0, '当前比例只能在0-1之间');
        }

        $result = app('repo_flying')->supplementConfigUpdate($params);

        return Response::sendData($result);
    }

    /**
     * @Desc:补池列表
     * @return string
     * @author: shiquan
     * @Time: 2023/3/8 13:10
     */
    public function supplementGiftList()
    {
        $result = app('repo_flying')->supplementGiftList();

        return Response::sendData($result);
    }

    /**
     * @Desc:补池筛选礼物列表
     * @return string
     * @author: shiquan
     * @Time: 2023/3/8 13:13
     */
    public function nextCommonGifts()
    {
        $type = FlyingEnum::POOL_TYPE_HUNDRED_NEXT;
        $result = app('repo_flying')->nextCommonGifts($type);

        return Response::sendData($result);
    }

    /**
     * @Desc:补池礼物新增或者更新
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 13:17
     */
    public function supplementGiftUpdate(Request $request)
    {
        $params = $request->only(['gift_id', 'weight_num', 'id']);
        $params['id'] = intval($params['id'] ?? 0);
        if (empty($params['gift_id']) || $params['gift_id'] <= 0){
            throw new BasicException(0, '参数错误');
        }
        /*if (empty($params['weight_num']) || $params['weight_num'] < 0){
            throw new BasicException(0, '参数错误');
        }*/
        app('repo_flying')->supplementGiftUpdate($params);

        return Response::sendData(true);
    }

    /**
     * @Desc:补池礼物删除
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 13:20
     */
    public function supplementGiftDel(Request $request)
    {
        $params['id'] = intval($request->input('id',0));
        if ($params['id'] <= 0){
            throw new BasicException(0, '参数错误');
        }
        app('repo_flying')->supplementGiftDel($params);

        return Response::sendData(true);
    }

    /**
     * @Desc:暴击概率配置
     * @return string
     * @author: shiquan
     * @Time: 2023/3/8 15:32
     */
    public function criticalConfig()
    {
        $res = app('repo_flying')->criticalConfig();
        return Response::sendData($res);
    }

    /**
     * @Desc:暴击概率保存
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 15:32
     */
    public function criticalConfigSave(Request $request)
    {
        $params = $request->only(['config']);
        $v = app('validator')->make($params, [
            'config'   => 'required|json',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $res = app('repo_flying')->criticalConfigSave($params);
        return Response::sendData($res);
    }

}
